package com.example.houselease.web;

import com.example.houselease.ex.ServiceException;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;

import java.io.Serializable;

/**
 * 响应客户端数据 JSON类
 * */
@Data
public class JsonResult<T> implements Serializable {
    /**
     * 响应状态
     * */
    @ApiModelProperty("响应状态")
    private Integer state;

    /**
     * 响应信息
     * */
    @ApiModelProperty("响应信息")
    private String message;

    /**
     * 响应数据
     * */
    @ApiModelProperty("响应数据")
    private T data;

    private JsonResult() {
    }

    public JsonResult(ServiceCode state, String mes) {
        this.state = state.getValue();
        this.message = mes;
    }

    public JsonResult(ServiceCode state, T data) {
        this.state = state.getValue();
        this.data = data;
    }

    private JsonResult(Integer state) {
        this.state = state;
    }

    private JsonResult(Integer state, String message) {
        this.state = state;
        this.message = message;
    }

    /**
     * 响应成功
     * @return 响应成功状态码
     * */
    public static JsonResult<Void> ok(){
        return JsonResult.ok(null);
    }

    /**
     * 响应JSON数据
     * @param data 数据
     * @return 响应JSON数据
     * */
    public static <T> JsonResult<T> ok(T data){
        JsonResult<T> jsonResult = new JsonResult<T>(ServiceCode.OK.getValue());
        jsonResult.setData(data);
        return jsonResult;
    }

    /**
     * fail方法重载
     * @param e 异常
     * */
    public static JsonResult<Void> fail(ServiceException e){
        return fail(e.getServiceCode(),e.getMessage());
    }

    /**
     * 响应失败
     * @param state 状态码
     * @param mes 数据
     * @return 响应失败数据
     * */
    public static JsonResult<Void> fail(ServiceCode state,String mes){
        return new JsonResult<Void>(state.getValue(),mes);
    }
}
